package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.ReservationStatus;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ReservationVo;
import com.zzyl.vo.TimeCountVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class ReservationServiceImpl implements ReservationService {

    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 根据id删除预约
     */
    @Override
    public void deleteById(Long id) {
        reservationMapper.deleteById(id);
    }

    /**
     * 根据id查找预约
     */
    @Override
    public ReservationVo findById(Long id) {
        Reservation reservation = reservationMapper.findById(id);
        if (reservation != null) {
            return convertToVO(reservation);
        }
        return null;
    }


    /**
     * 查找所有预约
     * @param mobile 预约人手机号
     * @param time 预约时间
     */
    @Override
    public List<ReservationVo> findAll(String mobile, LocalDateTime time) {
        LocalDateTime endTime = time.plusHours(24); // 计算24小时后的时间
        Long userId = UserThreadLocal.getUserId();
        List<Reservation> reservations = reservationMapper.findAll(userId, mobile, time, endTime); // 根据mobile和时间范围查询预约
        return convertToVOList(reservations);
    }



    /**
     * 分页查找预约
     * @param page 页码
     * @param size 每页大小
     * @param name 预约人姓名
     * @param phone 预约人手机号
     * @param status 预约状态
     * @param type 预约类型
     * @param startTime
     * @param endTime
     * @return 预约列表
     */
    @Override
    public PageResponse<ReservationVo> findByPage(int page, int size, String name, String phone, Integer status, Integer type, LocalDateTime startTime, LocalDateTime endTime) {
        PageHelper.startPage(page, size);
        Long userId = UserThreadLocal.getUserId();
        Page<Reservation> byPage = reservationMapper.findByPage(page, size, name, phone, status, type, userId, startTime, endTime);
        return PageResponse.of(byPage, ReservationVo.class);
    }


    /**
     * 将Reservation转换为ReservationVO
     */
    private ReservationVo convertToVO(Reservation reservation) {
        return BeanUtil.toBean(reservation, ReservationVo.class);
    }

    /**
     * 将List<Reservation>转换为List<ReservationVO>
     */
    private List<ReservationVo> convertToVOList(List<Reservation> reservations) {
        return reservations.stream().map(this::convertToVO).collect(Collectors.toList());
    }



    /**
     * 查询每个时间段剩余预约次数
     * @param time 时间 日
     * @return 每个时间段剩余预约次数
     */
    @Override
    public List<TimeCountVo> countReservationsForEachTimeWithinTimeRange(LocalDateTime time) {
        LocalDateTime endTime = time.plusHours(24);
        return reservationMapper.countReservationsForEachTimeWithinTimeRange(time, endTime);
    }




    /**
     * 查询取消预约数量
     *
     * @return
     */
    @Override
    public Integer cancelledCount() {
        Long createBy = UserThreadLocal.getUserId();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime beginTime = LocalDateTimeUtil.beginOfDay(now);
        LocalDateTime endTime = LocalDateTimeUtil.endOfDay(now);
        return reservationMapper.cancelledCount(createBy,ReservationStatus.CANCELED.getOrdinal(),beginTime,endTime);
    }

    /**
     * 新增预约
     *
     * @param dto
     */
    @Override
    public void addReservation(ReservationDto dto) {
        Long userId = UserThreadLocal.getUserId();

        Reservation reservation = new Reservation();
        BeanUtil.copyProperties(dto, reservation);
        reservation.setCreateBy(userId);
        reservation.setStatus(ReservationStatus.PENDING.getOrdinal());
        System.out.println(reservation);
//        try {
            reservationMapper.addReservation(reservation);
//        } catch (Exception e) {
//            throw new BaseException("新增失败");
//        }

    }

    /**
     * 分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResponse<ReservationVo> findPage(Integer pageNum, Integer pageSize, Integer status) {

        //设置页数页码
        PageHelper.startPage(pageNum, pageSize);
        //获取当前用户
        Long createBy = UserThreadLocal.getUserId();
        //分页查询
        Page<ReservationVo> page = reservationMapper.findPage(status,createBy);

        return PageResponse.of(page, ReservationVo.class);
    }

    /**
     * 按照时间修改状态
     *
     * @param now
     */
    @Override
    public void updateReservationStatus(LocalDateTime now) {
        reservationMapper.updateReservationStatus(now);
    }


    /**
     * 统计每个时间段的预约次数
     *
     * @param time
     * @return
     */
    @Override
    public List<TimeCountVo> countByTime(Long time) {
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);
        log.info("时间：{}", localDateTime);
        List<TimeCountVo> vos = reservationMapper.countByTime(localDateTime);
        return vos;
    }

    /**
     * 取消预约
     *
     * @param id
     */
    @Override
    public void cancelReservation(Long id) {
        reservationMapper.cancelReservation(id,ReservationStatus.CANCELED.getOrdinal());
    }
}

